import { FastifyPluginAsync } from "fastify";
import { ObjectId } from "mongodb";
import { CommentDocument } from "../../../models/schemas";

interface CreateCommentRequest {
  orderId: string;
  content: string;
  parentId?: string;
  author: string;
  isAdmin?: boolean;
}

const createCommentRoutes: FastifyPluginAsync = async (
  fastify,
  opts,
): Promise<void> => {
  fastify.post(
    "/create-comment",
    {
      schema: {
        body: {
          type: "object",
          required: ["orderId", "content", "author"],
          properties: {
            orderId: { type: "string" },
            content: { type: "string" },
            parentId: { type: "string" },
            author: { type: "string" },
            isAdmin: { type: "boolean" },
          },
        },
        response: {
          201: {
            type: "object",
            properties: {
              success: { type: "boolean" },
              data: {
                type: "object",
                properties: {
                  commentId: { type: "string" },
                  orderId: { type: "string" },
                  content: { type: "string" },
                  author: { type: "string" },
                  createdAt: { type: "number" },
                },
              },
            },
          },
          400: {
            type: "object",
            properties: {
              success: { type: "boolean" },
              error: { type: "string" },
            },
          },
          500: {
            type: "object",
            properties: {
              success: { type: "boolean" },
              error: { type: "string" },
            },
          },
        },
      },
    },
    async (request, reply) => {
      const db = fastify.mongo.db;
      if (!db) {
        return reply.code(500).send({
          success: false,
          error: "数据库连接失败",
        });
      }

      const {
        orderId,
        content,
        parentId,
        author,
        isAdmin = false,
      } = request.body as CreateCommentRequest;

      try {
        // 验证订单是否存在
        const orderExists = await db.collection("orders").findOne({
          _id: new ObjectId(orderId),
        });

        if (!orderExists) {
          return reply.code(400).send({
            success: false,
            error: "订单不存在",
          });
        }

        // 如果是回复，验证父评论是否存在
        if (parentId) {
          const parentComment = await db.collection("comments").findOne({
            _id: new ObjectId(parentId),
          });

          if (!parentComment) {
            return reply.code(400).send({
              success: false,
              error: "父评论不存在",
            });
          }
        }

        // 创建新评论
        const newComment: Omit<CommentDocument, "_id"> = {
          orderId: new ObjectId(orderId),
          parentId: parentId ? new ObjectId(parentId) : undefined,
          content,
          author,
          isAdmin,
          createdAt: Date.now(),
          updatedAt: Date.now(),
        };

        const result = await db
          .collection<CommentDocument>("comments")
          .insertOne(newComment as any);

        return reply.code(201).send({
          success: true,
          data: {
            commentId: result.insertedId.toString(),
            orderId,
            content,
            author,
            createdAt: newComment.createdAt,
          },
        });
      } catch (error) {
        fastify.log.error(error);
        return reply.code(500).send({
          success: false,
          error: "服务器内部错误",
        });
      }
    },
  );
};

export default createCommentRoutes;
